package com.haochang.chunkvod.controller.activity.hostess;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import org.json.JSONObject;

import com.haochang.base.BaseActivity;
import com.haochang.base.BaseEditText;
import com.haochang.base.BaseTextView;
import com.haochang.base.OnBaseClickListener;
import com.haochang.chunkvod.R;
import com.haochang.chunkvod.app.common.intent.IntentCode;
import com.haochang.chunkvod.app.common.intent.IntentKey;
import com.haochang.chunkvod.app.config.ApiConfig;
import com.haochang.chunkvod.app.config.DeviceConfig;
import com.haochang.chunkvod.app.config.ServerErrorCodeConfig;
import com.haochang.chunkvod.app.utils.ScreenUtils;
import com.haochang.chunkvod.app.utils.SoftKeyboardUtils;
import com.haochang.chunkvod.app.utils.ToastUtils;
import com.haochang.chunkvod.model.cash.PrintEnum;
import com.haochang.chunkvod.model.cash.PrintInfo;
import com.haochang.chunkvod.model.hostess.HostessData;
import com.haochang.chunkvod.model.hostess.HostessInfo;
import com.haochang.chunkvod.tools.vod.log.Logger;
import com.haochang.chunkvod.tools.vod.other.DipPxConversion;
import com.haochang.chunkvod.tools.vod.thread.PrintThread;
import com.haochang.chunkvod.tools.vod.thread.ThreadPoolUtil;
import com.haochang.chunkvod.view.vod.ViewGroup.CustomFlowLayout;
import com.haochang.chunkvod.view.vod.activity.AuthorizationDialogActivity;
import com.haochang.chunkvod.view.vod.dialog.ActivityDialogItemInfo;
import com.haochang.chunkvod.view.vod.dialog.ChooseActivityDialog;
import com.haochang.chunkvod.view.vod.dialog.DialogItemInfo;
import com.haochang.chunkvod.view.vod.dialog.KeyBoardDialog;
import com.haochang.chunkvod.view.vod.dialog.SingleSelectionDialog;
import com.haochang.chunkvod.view.vod.popupWindow.VodPopWindow;
import com.haochang.chunkvod.view.vod.title.TitleView;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;

/**
 * @author Yangjie
 *         className ReserveActivity
 *         created at  2016/8/23  18:08
 *         咨客 可用房型/一键开房
 */
public class OneKeyOpenRoomActivity extends BaseActivity implements KeyBoardDialog.KeyBoardOnSureListener, CustomFlowLayout.OnSingleCheckedChangeListener_
{

	private TitleView titleView;
	//房间用途选择文本
	private CustomFlowLayout flowLayout;
	//人数，备注输入框
	private BaseEditText et_count, et_desc;
	// 选择活动
	private BaseTextView room_choice_activity;
	// 权限验证
	private BaseTextView room_grant;
	//权限验证下方的文本,需要根据是否验证改变字体颜色
	private BaseTextView tv_room_none_time, tv_room_none_h, tv_room_none_m, tv_room_fees, room_fees, tv_room_room_type, room_room_type;
	//接受点击的横栏
	private LinearLayout group_room_fees, group_room_room_type;
	// 预结时间输入框
	private BaseEditText room_pre_h, room_pre_m;
	// 打印，大客户复选框
	private CheckBox checkBox_print, checkBox_big_customer;
	//确定按钮
	private BaseTextView room_ok;
	//授权是否成功小icon及右箭头隐藏
	private ImageView iv_granted_success, iv_arrow_right;
	//顶部选择房型textview
	private BaseTextView tv_choosed_room_type;


	private HostessData hostessData;
	private boolean firstSuccess = false;
	//存储所有功能
	private String[] usageCode;
	//当前选择的功能编号,默认为唱歌
	private int current_UsageCode = 0;

	//当前被点击的输入框
	private BaseEditText current_et;
	//是否已通过权限验证
	private boolean hasAuthorized = false;
	//当前计费方式
	private int currentFeesType = 0;
	// 所有计费方式
	private ArrayList<DialogItemInfo> listFees = new ArrayList<DialogItemInfo>();
	//当前计费房型
	private String currentRoomType = "请先选择房型";
	private ArrayList<DialogItemInfo> listRoomType = new ArrayList<DialogItemInfo>();
	///////////////////////////////////////////////////////////////////////////
	// 以下为第一个选择房型 及选择活动
	///////////////////////////////////////////////////////////////////////////
	//当前选择开房类型
	private String currentRoomTypeDesign = "";
	//当前选择活动
	private String currentActivity = "";
	private ArrayList<DialogItemInfo> listChooseRoomType = new ArrayList<DialogItemInfo>();
	private ArrayList<ActivityDialogItemInfo> listChooseActivity = new ArrayList<ActivityDialogItemInfo>();//活动
	private JSONObject jsonObjectActive;//保存所有活动的JSONObject
	private long lastTimeFromNet;//最近一次服务器时间
	private long lastTimeLocal;//最近一次本地时间
	private String reservationTime;//预结时间
	private String authCode = "";//权鉴的code
	private DialogItemInfo itemInfo;//当前房型选择的item缓存；

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
	}

	@Override
	public void receiveParam()
	{
	}

	@Override
	public void initData()
	{
		hostessData = new HostessData(this);
	}

	@Override
	public void onResume()
	{
		super.onResume();
		SoftKeyboardUtils.closeSoftKeyBoard(this, et_count);
		if (!firstSuccess)
		{
			ToastUtils.showText(OneKeyOpenRoomActivity.this, "正在获取房间信息...");
			requestOneKeyOpenRoomInfo();
		}
	}

	@Override
	public void initViews()
	{
		setContentView(R.layout.activity_onekey_openroom);
		initView();
		titleView = (TitleView) findViewById(R.id.titleView);
		titleView.setTitle(R.string.room_setting_type).setTitleOnClickListener(new TitleView.ITitleOnClickListener()
		{
			@Override
			public void onBackClick()
			{
				finish();
				animRightToLeft();
			}

			@Override
			public void onDoneClick()
			{
				List<String> list = new ArrayList<String>();
				list.add("回到首页");
				list.add("修改密码");
				list.add("退出登录");
				int location[] = new int[2];
				ImageView img = (ImageView) titleView.findViewById(R.id.img_operates);
				img.getLocationOnScreen(location);
				int x = location[0];
				final VodPopWindow pop = new VodPopWindow(OneKeyOpenRoomActivity.this, list);
				pop.showPopupWindow(titleView, x);
				pop.setPopWindowListListener(new VodPopWindow.OnPopWindowListListener()
				{
					@Override
					public void onSelectItem(int position)
					{
						switch (position)
						{
						case 0:
							backToHome();
							break;
						case 1:
							goToPasswordModify();
							break;
						case 2:
							loginOut();
							break;

						default:
							break;
						}
					}
				});
			}
		});
	}

	private void initView()
	{
		LinearLayout group_room_choice_activity = (LinearLayout) findViewById(R.id.group_room_choice_activity);
		LinearLayout group_room_grant = (LinearLayout) findViewById(R.id.group_room_grant);
		LinearLayout linear_choose_room_type = (LinearLayout) findViewById(R.id.linear_choose_room_type);
		tv_choosed_room_type = (BaseTextView) findViewById(R.id.tv_choosed_room_type);
		iv_arrow_right = (ImageView) findViewById(R.id.iv_arrow_right);
		iv_granted_success = (ImageView) findViewById(R.id.iv_granted_success);
		flowLayout = (CustomFlowLayout) findViewById(R.id.flowLayout);

		et_count = (BaseEditText) findViewById(R.id.et_count);
		et_desc = (BaseEditText) findViewById(R.id.et_desc);
		room_choice_activity = (BaseTextView) findViewById(R.id.room_choice_activity);
		room_grant = (BaseTextView) findViewById(R.id.room_grant);
		tv_room_none_time = (BaseTextView) findViewById(R.id.tv_room_none_time);
		tv_room_none_h = (BaseTextView) findViewById(R.id.tv_room_none_h);
		tv_room_none_m = (BaseTextView) findViewById(R.id.tv_room_none_m);
		tv_room_fees = (BaseTextView) findViewById(R.id.tv_room_fees);
		room_fees = (BaseTextView) findViewById(R.id.room_fees);
		tv_room_room_type = (BaseTextView) findViewById(R.id.tv_room_room_type);
		room_room_type = (BaseTextView) findViewById(R.id.room_room_type);
		room_pre_h = (BaseEditText) findViewById(R.id.room_pre_h);
		room_pre_m = (BaseEditText) findViewById(R.id.room_pre_m);
		checkBox_print = (CheckBox) findViewById(R.id.checkBox_print);
		checkBox_big_customer = (CheckBox) findViewById(R.id.checkBox_big_customer);
		room_ok = (BaseTextView) findViewById(R.id.room_ok);
		group_room_fees = (LinearLayout) findViewById(R.id.group_room_fees);
		group_room_room_type = (LinearLayout) findViewById(R.id.group_room_room_type);

		et_count.setOnClickListener(etClickListener);
		room_pre_h.setOnClickListener(etClickListener);
		room_pre_m.setOnClickListener(etClickListener);

		room_pre_h.addTextChangedListener(watcher);
		room_pre_m.addTextChangedListener(watcher);

		group_room_choice_activity.setOnClickListener(mOnBaseClickListener);
		group_room_grant.setOnClickListener(mOnBaseClickListener);
		group_room_fees.setOnClickListener(mOnBaseClickListener);
		group_room_room_type.setOnClickListener(mOnBaseClickListener);
		linear_choose_room_type.setOnClickListener(mOnBaseClickListener);
		room_ok.setOnClickListener(mOnBaseClickListener);

		hasAuthorized = true;
		refreshAuthorizationView();
	}

	private TextWatcher watcher = new TextWatcher()
	{
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after)
		{

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count)
		{
			if (Integer.parseInt(room_pre_h.getText().toString().trim()) > 23)
			{
				room_pre_h.setText(String.valueOf(23));
			}
			if (Integer.parseInt(room_pre_m.getText().toString().trim()) > 59)
			{
				room_pre_m.setText(String.valueOf(59));
			}
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
			SimpleDateFormat simpleDateFormatDay = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
			DecimalFormat decimalFormat = (DecimalFormat) NumberFormat.getInstance();
			decimalFormat.applyPattern("00");
			String time = "";
			long currenTimeFromNet = lastTimeFromNet + (System.currentTimeMillis() - lastTimeLocal);//点击时计算服务器当前时间
			try
			{
				time = simpleDateFormatDay.format(simpleDateFormat.parse(reservationTime)) + " "
						+ decimalFormat.format(Long.parseLong(room_pre_h.getText().toString())) + ":"
						+ decimalFormat.format(Long.parseLong(room_pre_m.getText().toString())) + ":00";
			} catch (Exception e)
			{
				Logger.e("按房型开房：" + e.getMessage());
			}
			Logger.e("time:" + time + "  " + currenTimeFromNet);
			try
			{
				Logger.e("设定:" + (simpleDateFormat.parse(time).getTime() - currenTimeFromNet));
				if ((simpleDateFormat.parse(time).getTime() - currenTimeFromNet <= 30 * 60 * 1000))
				{
					room_ok.setClickable(false);
					room_ok.setEnabled(false);
					room_ok.setBackgroundResource(R.drawable.shape_gray);
					ToastUtils.showText(OneKeyOpenRoomActivity.this, String.format(Locale.getDefault(), "预结时间离当前时间已不足%d分钟", 30));
				} else
				{
					room_ok.setClickable(true);
					room_ok.setEnabled(true);
					room_ok.setBackgroundResource(R.drawable.dialog_sure_btn);
				}
			} catch (Exception e)
			{
				Logger.e("按房型开房_ 文本变化：" + e.getMessage());
			}
		}

		@Override
		public void afterTextChanged(Editable s)
		{

		}
	};

	/**
	 * 数字输入框点击事件监听
	 */
	private OnBaseClickListener etClickListener = new OnBaseClickListener()
	{
		@Override
		public void onBaseClick(View v)
		{
			current_et = (BaseEditText) v;
			KeyBoardDialog keyBoardDialog = new KeyBoardDialog(OneKeyOpenRoomActivity.this);
			keyBoardDialog.setKeyBoardOnSureListener(OneKeyOpenRoomActivity.this);
			keyBoardDialog.show();
		}
	};

	/**
	 * 点击事件监听
	 */
	private OnBaseClickListener mOnBaseClickListener = new OnBaseClickListener()
	{

		@Override
		public void onBaseClick(View v)
		{
			Intent intent;
			switch (v.getId())
			{
			case R.id.group_room_grant:
				//权限验证
				if (!hasAuthorized)
				{
					intent = new Intent(OneKeyOpenRoomActivity.this, AuthorizationDialogActivity.class);
					intent.putExtra(IntentKey.INTERFACE_NAME, ApiConfig.PERMISSION_CHECK_OPEN_ROOM);//传入接口名字
					startActivityForResult(intent, IntentCode.HOSTESS_GRANT_REQUEST);
				}
				break;
			//下面是 选择活动
			case R.id.group_room_choice_activity:
				//选择活动
				if (TextUtils.isEmpty(currentRoomTypeDesign))
				{
					ToastUtils.showText(OneKeyOpenRoomActivity.this, "请先选择房型");
					return;
				}
				//先请求
				if (listChooseActivity.size() > 0)
				{
					ActivityDialogItemInfo info = new ActivityDialogItemInfo("-1", "不选择活动", true);
					info.setId("");
					listChooseActivity.add(info);
				} else
				{
					ToastUtils.showText(OneKeyOpenRoomActivity.this, "该房间暂无活动");
					return;
				}
				new ChooseActivityDialog.Builder(OneKeyOpenRoomActivity.this).setTitle("选择活动")
						.setSingleChoiceItems(listChooseActivity, new ChooseActivityDialog.OnSingleChoosedListner()
						{
							@Override
							public void onSingleChoosed(ActivityDialogItemInfo info)
							{
								room_choice_activity.setText(info.getName());
								currentActivity = info.getId();
								Logger.e("选择活动id:" + info.getId());
							}
						}).showDialog(8);
				break;
			//下面是 计费方式
			case R.id.group_room_fees:
				if (listFees.size() <= 0)
				{
					ToastUtils.showText(OneKeyOpenRoomActivity.this, "正在获取房间信息...");
					requestOneKeyOpenRoomInfo();
					return;
				}
				//选择计费方式
				new SingleSelectionDialog.Builder(OneKeyOpenRoomActivity.this).setTitle("计费方式")
						.setSingleChoiceItems(listFees, new SingleSelectionDialog.OnSelectListener()
						{
							@Override
							public void getValue(String code, String name)
							{
								room_fees.setText(name);
								try
								{
									currentFeesType = Integer.parseInt(code);
								} catch (NumberFormatException e)
								{
									currentFeesType = 0;
								}
							}
						}).createDialog(5).show();
				break;
			//下面是 计费房型
			case R.id.group_room_room_type:
				if (listRoomType.size() <= 0)
				{
					ToastUtils.showText(OneKeyOpenRoomActivity.this, "正在获取房间信息...");
					requestOneKeyOpenRoomInfo();
					return;
				}
				new SingleSelectionDialog.Builder(OneKeyOpenRoomActivity.this).setTitle("计费房型")
						.setSingleChoiceItems(listRoomType, new SingleSelectionDialog.OnSingleItemChoosedListener()
						{
							@Override
							public void getSelectedItem(DialogItemInfo itemInfo)
							{
								room_room_type.setText(itemInfo.getTitle());
								currentRoomType = itemInfo.getId();
							}
						}).createDialog(5).show();
				break;
			//下面是 选择房型
			case R.id.linear_choose_room_type:
				//顶部选择房型
				//先请求
				if (listChooseRoomType != null && listChooseRoomType.size() > 0)
				{
					new SingleSelectionDialog.Builder(OneKeyOpenRoomActivity.this).setTitle("选择房型")
							.setSingleChoiceItems(listChooseRoomType, new SingleSelectionDialog.OnSingleItemChoosedListener()
							{
								@Override
								public void getSelectedItem(DialogItemInfo itemInfo)
								{
									OneKeyOpenRoomActivity.this.itemInfo = itemInfo;
									tv_choosed_room_type.setText(itemInfo.getName());
									currentRoomTypeDesign = itemInfo.getId();
									refreshActivity(jsonObjectActive, itemInfo.getId());
									currentRoomType = itemInfo.getId();
									refreshOterData(itemInfo);
								}
							}).createDialog(6).show();
				} else
				{
					ToastUtils.showText(OneKeyOpenRoomActivity.this, "正在获取房间信息...");
					requestOneKeyOpenRoomInfo();
				}

				break;
			case R.id.room_ok:
				//点击ok按钮 提交数据
				commit();
				break;
			}
		}
	};

	/**
	 * 提交开房请求
	 */
	private void commit()
	{
		if (isLegal())
		{
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("room_type_id", currentRoomTypeDesign);//房型ID
			map.put("customer_count", et_count.getText().toString());//顾客人数
			map.put("active_id", currentActivity);//账单参加活动
			map.put("usage", usageCode[current_UsageCode]);//房间用途
			map.put("remarks", null == et_desc.getText() ? "" : et_desc.getText().toString());//备注
			map.put("is_honor", checkBox_big_customer.isChecked() ? "1" : "0");//是否大客户
			if (!TextUtils.isEmpty(authCode))
			{
				SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
				SimpleDateFormat simpleDateFormatDay = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
				DecimalFormat decimalFormat = (DecimalFormat) NumberFormat.getInstance();
				decimalFormat.applyPattern("00");
				String time = "";
				try
				{
					time = simpleDateFormatDay.format(simpleDateFormat.parse(reservationTime)) + " "
							+ decimalFormat.format(Long.parseLong(room_pre_h.getText().toString())) + ":"
							+ decimalFormat.format(Long.parseLong(room_pre_m.getText().toString())) + ":00";
				} catch (Exception e)
				{
					Logger.e("按房型开房_提交开房请求：" + e.getMessage());
				}
				Logger.e("time:" + time);
				map.put("charging_policy", currentFeesType + "");//计费策略
				map.put("expected_time", time);//预结时间
				map.put("charging_room_type_id", currentRoomType);//计费房型id
				map.put("auth_code", authCode);//管理员授权码
			}
			hostessData.requestOneKeyOpenRoom(map, true, new HostessData.ResultResponse()
			{
				@Override
				public void onRequestSuccess()
				{
					openRoomSuccessed();
				}

				@Override
				public void onFail(int errorNo, String errorMsg)
				{
					Logger.e("errorNo:" + errorNo);
					Logger.e("errorMsg:" + errorMsg);
					if (errorNo == ServerErrorCodeConfig.ROOMS_COUNTS_ZERO)
					{
						//房间个数为0
						requestOneKeyOpenRoomInfo(1);
					} else if (errorNo == ServerErrorCodeConfig.TIMES_ERROR)
					{
						//预结时间错误
						requestEndTime(currentRoomTypeDesign);
					} else if (errorNo == ServerErrorCodeConfig.AUTHORIZATION_ERROR)
					{
						//这个是授权码错误
						//先将预结时间恢复到默认
						SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
						SimpleDateFormat simpleDateFormatHH = new SimpleDateFormat("HH", Locale.getDefault());
						SimpleDateFormat simpleDateFormatmm = new SimpleDateFormat("mm", Locale.getDefault());
						try
						{
							room_pre_h.setText(simpleDateFormatHH.format(simpleDateFormat1.parse(reservationTime)));
							room_pre_m.setText(simpleDateFormatmm.format(simpleDateFormat1.parse(reservationTime)));
						} catch (Exception e)
						{
							room_pre_h.setText("0");
							room_pre_m.setText("0");
						}
						resumeRoomPolicies();
						//重新授权
						hasAuthorized = false;
						authCode = "";
						refreshAuthorizationView();
						ToastUtils.showText(OneKeyOpenRoomActivity.this, TextUtils.isEmpty(errorMsg) ? "权限验证失败!" : errorMsg);
					} else
					{
						ToastUtils.showText(OneKeyOpenRoomActivity.this, TextUtils.isEmpty(errorMsg) ? "开启房间失败!" : errorMsg);
					}
				}
			});
		}
	}

	/**
	 * 判断输入合法性
	 * @return 是否合法
	 */
	private boolean isLegal()
	{
		if (TextUtils.isEmpty(currentRoomTypeDesign))
		{
			ToastUtils.showText(OneKeyOpenRoomActivity.this, "请先选择房型");
			return false;
		} else if (TextUtils.isEmpty(et_count.getText().toString()))
		{
			ToastUtils.showText(OneKeyOpenRoomActivity.this, "请输入人数");
			return false;
		}
		return true;
	}

	/**
	 * 开房成功后的操作
	 */
	private void openRoomSuccessed()
	{
		ToastUtils.showText(OneKeyOpenRoomActivity.this, checkBox_print.isChecked() ? "开房成功,正在打印带客单!" : "开房成功!");
		if (checkBox_print.isChecked())
		{
			printList();
		}
		setResult(Activity.RESULT_OK);
		finish();

	}

	/**
	 * 打印带客单
	 */
	private void printList()
	{
		//判断是否用的是P2000的设备
		if (DeviceConfig.isUseP2000Device())
		{
			final PrintInfo printInfo = new PrintInfo();
			printInfo.setType(PrintEnum.PRINT_HOSTESS_ONE_KEY_OPEN_ROOM.getName());
			printInfo.setContent("OneKeyOpenRoom");
			ThreadPoolUtil.getInstanceSingleTaskExecutor().submit(new PrintThread(PrintEnum.PRINT_HOSTESS_ONE_KEY_OPEN_ROOM, printInfo));
			ThreadPoolUtil.getInstanceSingleTaskExecutor().submit(new PrintThread(PrintEnum.PRINT_HOSTESS_ONE_KEY_OPEN_ROOM, printInfo));
		} else
		{
			ToastUtils.showText(OneKeyOpenRoomActivity.this, "您的设备不支持打印功能!");
		}
	}

	@Override
	public void setValue(String value)
	{
		try
		{
			if (value.contains("."))
				ToastUtils.showText(this, R.string.error_number);
			else if (Integer.parseInt(value) <= 0)
				ToastUtils.showText(this, R.string.error_number);
			else
				current_et.setText(value);
		} catch (Exception e)
		{
			ToastUtils.showText(OneKeyOpenRoomActivity.this, getResources().getString(R.string.error_max_number));
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == IntentCode.HOSTESS_GRANT_REQUEST && resultCode == RESULT_OK && data != null)
		{
			authCode = data.getStringExtra(IntentKey.GRANT_DIALOG_TOKEN);
			//调用权限验证接口
			hasAuthorized = true;
			refreshAuthorizationView();
		}
	}

	/**
	 * 恢复默认 房间计费策略
	 */
	private void resumeRoomPolicies()
	//房间计费策略
	{
		room_fees.setText(listFees.get(0).getName());
		currentFeesType = 0;
		room_room_type.setText(itemInfo.getTitle());
		currentRoomType = itemInfo.getId();
		//这个是将计费房型dialog同步
		if (listRoomType.size() > 0)
		{
			String policyRoomType = itemInfo.getTitle();
			int len = listRoomType.size();
			for (int i = 0; i < len; i++)
			{
				DialogItemInfo info = listRoomType.get(i);
				info.setSelected(!TextUtils.isEmpty(policyRoomType) && TextUtils.equals(info.getTitle(), policyRoomType));
			}
		}
	}

	/**
	 * 根据权限是否验证通过显示下方的内容
	 */
	private void refreshAuthorizationView()
	{
		int color;
		int colorTv;
		if (hasAuthorized)
		{
			color = this.getResources().getColor(R.color.color_282828);
			colorTv = this.getResources().getColor(R.color.color_737373);
			room_pre_h.setEnabled(true);
			room_pre_m.setEnabled(true);
			group_room_fees.setEnabled(true);
			group_room_room_type.setEnabled(true);
			iv_granted_success.setImageResource(R.drawable.ic_success);
			room_grant.setText("已通过");
			room_grant.setTextColor(getResources().getColor(R.color.color_4bbb4d));
			iv_arrow_right.setVisibility(View.GONE);
		} else
		{
			color = this.getResources().getColor(R.color.color_a9a9a9);
			colorTv = this.getResources().getColor(R.color.color_a9a9a9);
			room_pre_h.setEnabled(false);
			room_pre_m.setEnabled(false);
			group_room_fees.setEnabled(false);
			group_room_room_type.setEnabled(false);
			iv_granted_success.setImageResource(R.drawable.ic_warn);
			room_grant.setText("未通过");
			room_grant.setTextColor(getResources().getColor(R.color.color_ffab40));
			iv_arrow_right.setVisibility(View.VISIBLE);
		}
		tv_room_none_time.setTextColor(color);
		room_pre_h.setTextColor(color);
		tv_room_none_h.setTextColor(colorTv);
		room_pre_m.setTextColor(color);
		tv_room_none_m.setTextColor(colorTv);
		tv_room_fees.setTextColor(color);
		room_fees.setTextColor(colorTv);
		tv_room_room_type.setTextColor(color);
		room_room_type.setTextColor(colorTv);
	}

	/**
	 * 刷新预结时间及选择的活动归零
	 *
	 * @param itemInfo 预结时间
	 */
	private void refreshOterData(DialogItemInfo itemInfo)
	{
		if (null != itemInfo)
		{
			String policyRoomType = itemInfo.getTitle();
			String endTime = itemInfo.getEndTime();
			room_choice_activity.setText("不选择活动");
			room_room_type.setText(policyRoomType);
			currentActivity = "";
			if (!TextUtils.isEmpty(endTime))
			{
				reservationTime = endTime;
				SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
				SimpleDateFormat simpleDateFormatHH = new SimpleDateFormat("HH", Locale.getDefault());
				SimpleDateFormat simpleDateFormatmm = new SimpleDateFormat("mm", Locale.getDefault());
				try
				{
					room_pre_h.setText(simpleDateFormatHH.format(simpleDateFormat1.parse(endTime)));
					room_pre_m.setText(simpleDateFormatmm.format(simpleDateFormat1.parse(endTime)));
				} catch (Exception e)
				{
					room_pre_h.setText("0");
					room_pre_m.setText("0");
				}
			}
			if (room_fees.getText().toString().contains("选择"))
			{
				if (listFees.size() > 0)
				{
					room_fees.setText((listFees.get(0)).getName());
					currentFeesType = 0;
				}
			}
			//这个是将计费房型dialog同步
			if (listRoomType.size() > 0)
			{
				int len = listRoomType.size();
				for (int i = 0; i < len; i++)
				{
					DialogItemInfo info = listRoomType.get(i);
					if (!TextUtils.isEmpty(policyRoomType) && TextUtils.equals(info.getTitle(), policyRoomType))
					{
						info.setSelected(true);
					} else
					{
						info.setSelected(false);
					}
				}
			}
			et_count.setText(itemInfo.getNumber());
		}
	}

	/**
	 * 刷新活动
	 *
	 * @param activeId 活动id
	 */
	private void refreshActivity(JSONObject jsonObjectActive, String activeId)
	{
		listChooseActivity.clear();
		ArrayList<ActivityDialogItemInfo> activityDialogItemInfos = hostessData.refreshActivity(jsonObjectActive, activeId);
		if (null != activityDialogItemInfos)
		{
			listChooseActivity.addAll(activityDialogItemInfos);
		}
	}

	private boolean hadAdded2;//是否已添加房间用途

	/**
	 * 房间用途
	 *
	 * @param list 名称列表
	 */
	private void initRoomUsage(List<String> list, List<String> listCode)
	{
		if (list != null && list.size() > 0)
		{
			if (flowLayout.getChildCount() <= 0)
			{
				int length = list.size();
				View[] views = new View[length];
				usageCode = new String[length];
				if (length > 0 && !hadAdded2)
				{
					int width = ScreenUtils.getScreenWidth(OneKeyOpenRoomActivity.this) / 5;
					int wrapDp = DipPxConversion.dip2px(OneKeyOpenRoomActivity.this, 70);
					int _20dp = DipPxConversion.dip2px(OneKeyOpenRoomActivity.this, 20);
					for (int j = 0; j < length; j++)
					{
						usageCode[j] = listCode.get(j);
						final ViewGroup viewGroup = null;
						LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(wrapDp, LinearLayout.LayoutParams.MATCH_PARENT);
						RadioButton radioButton = (RadioButton) LayoutInflater.from(OneKeyOpenRoomActivity.this).inflate(R.layout.inflate_flowlayot_usage,
								viewGroup);
						params.setMargins((width - wrapDp) / 2, 0, (width - wrapDp) / 2, _20dp);
						radioButton.setLayoutParams(params);
						radioButton.setText(list.get(j));
						if (j == 0)
						{
							radioButton.setChecked(true);
						} else
						{
							radioButton.setChecked(false);
						}
						views[j] = radioButton;
					}
					flowLayout.addData(views, true);
					hadAdded2 = true;
				}
			}
		}
	}

	private void requestEndTime(String room_type_id)
	{
		hostessData.requestOneKeyOpenRoomEndTime(false, room_type_id, new HostessData.ResultResponseList()
		{
			@Override
			public void onRequestSuccess(List list)
			{
				if (list != null && list.size() > 0)
				{
					String endTime = ((HostessInfo) list.get(0)).getEnd_time();
					SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
					SimpleDateFormat simpleDateFormatHH = new SimpleDateFormat("HH", Locale.getDefault());
					SimpleDateFormat simpleDateFormatmm = new SimpleDateFormat("mm", Locale.getDefault());
					try
					{
						room_pre_h.setText(simpleDateFormatHH.format(simpleDateFormat1.parse(endTime)));
						room_pre_m.setText(simpleDateFormatmm.format(simpleDateFormat1.parse(endTime)));
						ToastUtils.showText(OneKeyOpenRoomActivity.this, "最长预结时间为 " + simpleDateFormatHH.format(simpleDateFormat1.parse(endTime)) + ":"
								+ simpleDateFormatmm.format(simpleDateFormat1.parse(endTime)));
					} catch (Exception e)
					{
						room_pre_h.setText("0");
						room_pre_m.setText("0");
					}
				}
			}

			@Override
			public void onFail(int errno, String errMsg)
			{
				ToastUtils.showText(OneKeyOpenRoomActivity.this, "获取预结时间失败");
			}
		});

	}

	private void requestOneKeyOpenRoomInfo()
	{
		requestOneKeyOpenRoomInfo(0);
	}

	/**
	 * @param type type 0为初始化请求 1刷新房型可用房间
	 */
	@SuppressWarnings("unchecked")
	private void requestOneKeyOpenRoomInfo(final int type)
	{
		hostessData.requestOneKeyOpenRoomInfo(true, new HostessData.ResultResponseHashMap()
		{
			@Override
			public void onRequestSuccess(HashMap<String, Object> hashMap, boolean clear)
			{
				firstSuccess = true;
				if (hashMap != null && hashMap.size() > 0)
				{
					//处理服务器时间//预结时间相关
					if (hashMap.containsKey(IntentKey.SERVER_TIME))
					{
						lastTimeFromNet = (Long) (hashMap.get(IntentKey.SERVER_TIME)) * 1000;
						lastTimeLocal = System.currentTimeMillis();
					}
					//活动相关
					if (hashMap.containsKey(IntentKey.JSONObject))
					{
						jsonObjectActive = (JSONObject) hashMap.get(IntentKey.JSONObject);
					}
					//房间用途
					if (hashMap.containsKey(IntentKey.ROOM_USAGE))
					{
						List<String> list = (List<String>) hashMap.get(IntentKey.ROOM_USAGE);
						List<String> listCode = (List<String>) hashMap.get(IntentKey.ROOM_USAGE_CODE);
						initRoomUsage(list, listCode);
					}
					//计费方式
					if (hashMap.containsKey(IntentKey.FEE_TYPE_LIST))
					{
						listFees = (ArrayList<DialogItemInfo>) hashMap.get(IntentKey.FEE_TYPE_LIST);
						if (type == 1)
						{
							for (DialogItemInfo info : listFees)
							{
								if (TextUtils.equals(info.getCode(), currentFeesType + ""))
								{
									info.setSelected(true);
								} else
								{
									info.setSelected(false);
								}
							}
						}
					}
					//计费房型
					if (hashMap.containsKey(IntentKey.ROOM_TYPE_LIST))
					{
						listRoomType = (ArrayList<DialogItemInfo>) hashMap.get(IntentKey.ROOM_TYPE_LIST);
						if (type == 1)
						{
							if (!TextUtils.isEmpty(currentRoomType))
							{
								for (DialogItemInfo info : listRoomType)
								{
									if (TextUtils.equals(info.getId(), currentRoomType))
									{
										info.setSelected(true);
									} else
									{
										info.setSelected(false);
									}
								}
							}
						}
					}
					//顶部选择房型
					if (hashMap.containsKey(IntentKey.ROOM_TYPE_CHOOSE_LIST))
					{
						listChooseRoomType = (ArrayList<DialogItemInfo>) hashMap.get(IntentKey.ROOM_TYPE_CHOOSE_LIST);
						if (type == 1)
						{
							if (!TextUtils.isEmpty(currentRoomTypeDesign))
							{
								for (DialogItemInfo info : listChooseRoomType)
								{
									if (TextUtils.equals(info.getId(), currentRoomTypeDesign))
									{
										info.setSelected(true);
										tv_choosed_room_type.setText(info.getName());
									} else
									{
										info.setSelected(false);
									}
								}
							}
						}
					}
				}
			}

			@Override
			public void onFail()
			{
			}
		});
	}

	@Override
	public void onSingleCheckedChanged_(int position, boolean b, CompoundButton compoundButton)
	{
		current_UsageCode = position;
		Logger.e("onSingleCheckedChanged_:" + position);
	}
}
